package org.smoozik.services.sequence;

import java.util.ArrayList;

import org.smoozik.services.musictheory.Token;

public class RythmicPattern {
	ArrayList<Token> tokens;

	public RythmicPattern() {
		tokens = new ArrayList<>();
	}

	public ArrayList<Token> generateTokens() {
		ArrayList<Token> list = new ArrayList<>();
		for (Token token : tokens) {
			list.add(new Token(token));
		}

		return list;
	}

	public ArrayList<Token> getTokens() {
		return tokens;
	}

	public void setTokens(ArrayList<Token> tab) {
		this.tokens = tab;
	}

	public int size() {
		return tokens.size();
	}

	public void add(Token e) {
		tokens.add(e);
	}

	public Token get(int i) {
		i = i % tokens.size();
		return tokens.get(i);
	}

	public static RythmicPattern pattern1() {
		RythmicPattern r = basicPattern(2, 0.5);
		Token t = r.get(r.size() - 1);
		t.setDuration(t.getDuration() + 2);

		return r;
	}

	public double getTimeLength() {
		if (tokens == null) {
			return 0;
		}

		Token lastToken = null;

		if (0 == tokens.size()) {
			lastToken = tokens.get(0);
		} else {
			lastToken = tokens.get(tokens.size() - 1);
		}

		return lastToken.getPlace() + lastToken.getDuration();
	}

	public static RythmicPattern pattern2() {
		RythmicPattern r = new RythmicPattern();
		double place = 0;

		place = 0;
		r.addToken(0.5, place);
		place = 1;
		r.addToken(0.5, place);
		place = 2.5;
		r.addToken(0.5, place);
		place = 3.5;
		r.addToken(0.5, place);
		place = 5.5;
		r.addToken(0.5, place);
		place = 6.5;
		r.addToken(1.5, place);

		return r;
	}

	public void addToken(double duration, double place) {
		Token t = new Token();
		t.setPlace(place);
		t.setDuration(duration);
		t.setVelocity(80);

		add(t);
	}

	public static RythmicPattern basicPattern(double totalDuration, double duration) {
		RythmicPattern r = new RythmicPattern();
		Token tmp = null;
		double place = 0;

		do {
			tmp = new Token();
			tmp.setPlace(place);
			tmp.setDuration(duration);
			place += duration;
			r.add(tmp);
		} while (place < totalDuration);

		return r;
	}

	public String toString() {
		String s = "";

		for (Token t : tokens) {
			s += "place : " + t.getPlace() + " duration : " + t.getDuration()
					+ " velocity : " + t.getVelocity() + "\n";
		}

		return s;
	}
}
